#include "booklist.h"
#include "ui_booklist.h"
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlRecord>
#include "addbookdialog.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSslConfiguration>
#include <QSslCertificate>
#include <QFile>

// 构造函数，初始化UI和MQTT客户端
BookList::BookList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BookList),
    pMqttClient(new QMqttClient(this)),  // 初始化MQTT客户端
    lastDeleteTime(QDateTime::currentDateTime().addSecs(-6))  // 初始化为当前时间的6秒前
{
    ui->setupUi(this);  // 设置UI

    // 设置窗口标题
        this->setWindowTitle("智能家居管理系统");

    // 设置数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/hr/Desktop/088/sg.db");
    if (!db.open()) {
        QMessageBox::information(this, "连接结果", "连接数据库失败!");
        return;
    }

    // 设置模型
    model = new QSqlTableModel(this);
    model->setTable("Book");
    model->select();  // 查询所有书籍

    // 设置视图
    ui->tableView->setModel(model);
    ui->tableView->setColumnWidth(0, 150); // 设置 title 列的宽度为 150
    ui->tableView->setColumnWidth(1, 175); // 设置 author 列的宽度为 175
    ui->tableView->setColumnWidth(2, 125); // 设置 isbn 列的宽度为 125
    ui->tableView->setColumnWidth(3, 75);  // 设置 rfid 列的宽度为 75
    ui->tableView->setColumnWidth(4, 75);  // 设置 available 列的宽度为 75

    // 初始化MQTT客户端
      pMqttClient->setHostname("ma0a8495.ala.cn-hangzhou.emqxsl.cn");
      pMqttClient->setPort(8883);
      pMqttClient->setUsername("XingHuan_12");
      pMqttClient->setPassword("XingHuan");
      // SSL 配置
         QSslConfiguration sslConfig;
         QFile certFile("/home/hr/Desktop/088/emqxsl-ca.crt");
         certFile.open(QIODevice::ReadOnly);
         QSslCertificate certificate(&certFile, QSsl::Pem);
         sslConfig.setCaCertificates(QList<QSslCertificate>() << certificate);
    // 连接MQTT客户端的信号和槽
    connect(pMqttClient, &QMqttClient::stateChanged, this, &BookList::updateLogStateChange);
    connect(pMqttClient, &QMqttClient::messageReceived, this, &BookList::recv_message);
    connect(pMqttClient, &QMqttClient::connected, this, &BookList::onMqttConnected);  // 连接成功后订阅主题

    // 连接到MQTT服务器
    pMqttClient->connectToHostEncrypted();

    // 连接刷新按钮的信号和槽
    connect(ui->refreshButton, &QPushButton::clicked, this, &BookList::on_refreshButton_clicked);
}

// 析构函数，删除UI
BookList::~BookList()
{
    QSqlDatabase db = QSqlDatabase::database("uniqueConnectionName");
    if (db.isOpen()) {
        db.close();
    }
    QSqlDatabase::removeDatabase("uniqueConnectionName");
    delete ui;
}

// 更新日志状态变化
void BookList::updateLogStateChange()
{
    const QString content = QLatin1String(": State Change")
                    + QString::number(pMqttClient->state())
                    + QLatin1Char('\n');
    qDebug() << content;
}

// 接收MQTT消息
void BookList::recv_message(const QByteArray &message, const QMqttTopicName &topic)
{
    // 处理接收到的消息
    qDebug() << "Received message:" << message << " from topic:" << topic.name();

    // 解析JSON消息
    QJsonDocument doc = QJsonDocument::fromJson(message);
    if (!doc.isObject()) {
        qDebug() << "Invalid JSON received";
        return;
    }

    QJsonObject jsonObj = doc.object();
    QString title = jsonObj["title"].toString();
    QString author = jsonObj["author"].toString();
    QString isbn = jsonObj["isbn"].toString();
    QString available = jsonObj["available"].toString();
    QString rfid_tag = jsonObj["rfid_tag"].toString();
    QString username = jsonObj["username"].toString();

    // 更新书籍可用性
//    updateBookAvailability(rfid_tag, available, title, author, isbn);

    QSqlQuery query;
    query.prepare("SELECT available FROM Book WHERE rfid_tag = ?");
    query.addBindValue(rfid_tag);
    if (query.exec() && query.next()) {
        QString currentAvailability = query.value(0).toString();
        qDebug() << currentAvailability;
        if (currentAvailability == "0") {
            // 如果当前不可用，删除用户并更新可用性
            deleteLibraryUserByRfid(rfid_tag);
            updateAvailability(rfid_tag);
            qDebug() << "\n0";
            return;
        }
        qDebug() << "\nok";
        if (currentAvailability == "1") {
            // 如果当前可用，更新用户并更新可用性
            updateUser(username, rfid_tag);
            updateAvailability(rfid_tag);
            qDebug() << "\n1";
            return;
        }
    }
}


// MQTT连接成功后的槽函数
void BookList::onMqttConnected()
{
    pMqttClient->subscribe(QMqttTopicFilter("/089"));
    qDebug() << "Subscribed to topic: /089";
}

// 更新用户信息
void BookList::updateUser(const QString &username, const QString &rfid_tag)
{
    QSqlQuery query;
    query.prepare("SELECT * FROM LibraryUser WHERE rfid_tag = ?");
    query.addBindValue(rfid_tag);
    if (query.exec() && query.next()) {
        query.prepare("UPDATE LibraryUser SET username = ? WHERE rfid_tag = ?");
        query.addBindValue(username);
        query.addBindValue(rfid_tag);
        if (query.exec()) {
            qDebug() << "username更新成功";
        } else {
            qDebug() << "Failed to update username";
        }
    } else {
        qDebug() << "username不存在";
        if (!username.isEmpty() && !rfid_tag.isEmpty()) {
            query.prepare("INSERT INTO LibraryUser (username, rfid_tag) VALUES (?, ?)");
            query.addBindValue(username);
            query.addBindValue(rfid_tag);
            if (query.exec()) {
                qDebug() << "Created new user record";
            } else {
                qDebug() << "Failed to create new user record";
            }
        } else {
            qDebug() << "缺少username或rfid_tag";
        }
    }
}

// 根据RFID删除用户
void BookList::deleteLibraryUserByRfid(const QString &rfid_tag)
{
    QSqlQuery query;
    query.prepare("DELETE FROM LibraryUser WHERE rfid_tag = ?");
    query.addBindValue(rfid_tag);
    if (query.exec()) {
        qDebug() << "Library user with RFID" << rfid_tag << "has been deleted.";
    } else {
        qDebug() << "Failed to delete Library user with RFID" << rfid_tag;
    }
}

// 更新书籍可用性
void BookList::updateAvailability(const QString &rfid_tag)
{
    QSqlQuery query;
    query.prepare("SELECT available FROM Book WHERE rfid_tag = ?");
    query.addBindValue(rfid_tag);
    if (query.exec() && query.next()) {
        QString available = query.value(0).toString();
        if (available == "0"){
            query.prepare("UPDATE Book SET available = '1' WHERE rfid_tag = ?");
            query.addBindValue(rfid_tag);
        }else{
            query.prepare("UPDATE Book SET available = '0' WHERE rfid_tag = ?");
            query.addBindValue(rfid_tag);
        }
        if (query.exec()) {
            qDebug() << "\nupdateAvailability";
//            // 发布MQTT消息以控制设备
//            if (available == "1") {
//                pMqttClient->publish(QMqttTopicName("/control"), "1");
//            } else {
//                pMqttClient->publish(QMqttTopicName("/control"), "0");
//            }
        } else {
            qDebug() << "Failed to update book availability";
        }
    } else {
        qDebug() << "书籍不存在";
    }
}

// 打开灯带
void BookList::on_searchButton_clicked()
{
pMqttClient->publish(QMqttTopicName("BOOK/WS2812B_kz"), "M0");
}

// 打开窗帘
void BookList::on_addBookButton_clicked()
{
    pMqttClient->publish(QMqttTopicName("XingHuan/curtain_kz"), "0");
}

// 关闭灯带
void BookList::on_deleteButton_clicked()
{
//    //阈值管理
//    QDateTime currentTime = QDateTime::currentDateTime();
//    if (lastDeleteTime.secsTo(currentTime) < 5) {
//        QMessageBox::warning(this, "操作频繁", "删除操作间隔需超过5秒，请稍后再试！");
//        return;
//    }

//    // 删除选中书籍的逻辑
//    QModelIndexList selectedRows = ui->tableView->selectionModel()->selectedRows();
//    foreach (QModelIndex index, selectedRows) {
//        model->removeRow(index.row());  // 删除选中的行
//    }
//    model->submitAll();  // 提交所有更改
//    model->select();  // 重新查询所有书籍

//    // 更新上次删除操作时间
//    lastDeleteTime = currentTime;
    pMqttClient->publish(QMqttTopicName("BOOK/WS2812B_kz"), "W100");
}


//关闭窗帘
void BookList::on_refreshButton_clicked()
{

    pMqttClient->publish(QMqttTopicName("XingHuan/curtain_kz"), "1");
}

void BookList::on_refreshButton_3_clicked()
{

}

void BookList::on_refreshButton_4_clicked()
{

}
//自动模式
void BookList::on_refreshButton_2_clicked()
{
       pMqttClient->publish(QMqttTopicName("XingHuan/curtain_kz"), "2");
}
//最爱模式
void BookList::on_deleteButton_2_clicked()
{
        pMqttClient->publish(QMqttTopicName("BOOK/WS2812B_kz"), "M6");
}
